package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.adapter.Service_Adapter;
import com.example.xianji.BGARefresh.BGARefreshLayout;
import com.example.xianji.BGARefresh.BGARefreshLayout.BGARefreshLayoutDelegate;
import com.example.xianji.bean.Service;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;
import com.example.xianji.widgets.CustomProgressDialog;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

/**
 * 我发布的服务页面
 *
 * @author me
 */
public class Main_My_ServiceActivity extends Activity implements
        OnClickListener, BGARefreshLayoutDelegate {
    private RelativeLayout my_service_back;
    private CustomProgressDialog mCustomProgressDialog;
    //    private SharedPreferences sp;
//    private Editor ed;
    private ArrayList<Service> service_list = new ArrayList<Service>();
    private Service_Adapter mService_Adapter;
    private ListView sevice_mylistview;
    private BGARefreshLayout service_RefreshLayout;
    private int page = 1;
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    sevice_mylistview.setAdapter(mService_Adapter);
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.dismiss();
                        mCustomProgressDialog = null;
                    }
                    service_RefreshLayout.endRefreshing();
                    break;
                case 2:
                    mService_Adapter.notifyDataSetChanged();
                    service_RefreshLayout.endLoadingMore();
                    break;
                case 0:
                    if (mCustomProgressDialog != null) {
                        mCustomProgressDialog.show();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__my__service);
        my_service_back = (RelativeLayout) findViewById(R.id.my_relative_service_back);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        mService_Adapter = new Service_Adapter(this, service_list);
        sevice_mylistview = (ListView) findViewById(R.id.sevice_listview);
        service_RefreshLayout = (BGARefreshLayout) findViewById(R.id.service_RefreshLayout);

        mCustomProgressDialog = CustomProgressDialog.createDialog(this);
        mCustomProgressDialog.setCanceledOnTouchOutside(false);
        handler.sendEmptyMessageDelayed(0, 1000);

        get_service();
        my_service_back.setOnClickListener(this);
        service_RefreshLayout.setDelegate(this);
        processLogic(savedInstanceState);
    }

    protected void processLogic(Bundle savedInstanceState) {
        service_RefreshLayout
                .setRefreshViewHolder(new com.example.xianji.BGARefresh.BGANormalRefreshViewHolder(
                        this, true));
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.my_relative_service_back) {
            Main_My_ServiceActivity.this.finish();
        }
    }

    public void get_service() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("page", 1 + "");
        JSONObject params = new JSONObject(map);

        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.my_fuwu, params, new Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        service_list.clear();
                        JSONArray array = response.getJSONArray("data");
                        if (array.length() > 0) {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject obj = array.getJSONObject(i);
                                Service mService = new Service();
                                mService.setTitle(obj
                                        .getString("title"));
                                mService.setCreated_at(obj
                                        .getString("created_at"));
                                mService.setId(obj.getInt("id"));
                                service_list.add(mService);
                            }
                        } else {
                            Toast.makeText(
                                    Main_My_ServiceActivity.this,
                                    "您还没有发布服务哦", Toast.LENGTH_SHORT).show();
                        }
                        handler.sendEmptyMessage(1);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    public void get_service_more() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("page", page + "");
        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                Contant.my_fuwu, params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    if (response.getInt("status") == 1) {
                        JSONArray array = response.getJSONArray("data");
                        if (array.length() == 0) {
                            Toast.makeText(
                                    Main_My_ServiceActivity.this,
                                    "没有更多数据哦", Toast.LENGTH_SHORT).show();
                        } else {
                            for (int i = 0; i < array.length(); i++) {
                                JSONObject obj = array.getJSONObject(i);
                                Service mService = new Service();
                                mService.setTitle(obj
                                        .getString("title"));
                                mService.setCreated_at(obj
                                        .getString("created_at"));
                                mService.setId(obj.getInt("id"));
                                service_list.add(mService);
                            }
                        }
                        handler.sendEmptyMessage(2);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                if (mCustomProgressDialog != null) {
                    mCustomProgressDialog.dismiss();
                    mCustomProgressDialog = null;
                }
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    @Override
    public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
        new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                page = 1;
                get_service();
            }

        }.sendEmptyMessage(0);
    }

    @Override
    public boolean onBGARefreshLayoutBeginLoadingMore(
            BGARefreshLayout refreshLayout) {
        new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                page++;
                get_service_more();
            }
        }.sendEmptyMessage(0);
        return true;
    }
}
